<template>
  <div>
    <div class="" v-if="falg">
      <div class="basic">
        <div class="Useful">基本信息</div>

        <!-- 表单 -->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm" label-position="rigth">
          <el-form-item label="套餐名称" prop="name">
            <el-input v-model="ruleForm.name" maxlength="10" placeholder="请输入套餐名称" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="套餐描述" prop="describe">
            <el-input v-model="ruleForm.describe" maxlength="60" placeholder="请输入套餐描述" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="套餐定制描述" prop="orderdescribe">
            <el-input v-model="ruleForm.orderdescribe" maxlength="20" placeholder="请输入套餐定制描述" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="套餐标签" prop="tagname">
            <el-input v-model="ruleForm.tagname" placeholder="请输入套餐标签名称" maxlength="8" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="房屋面积配置" prop="goodsregion">
            <div v-for="(item, index) in ruleForm.goodsregion" :key="index" style="margin-bottom:5px;">
              <el-select v-model="ruleForm.goodsregion[index].areaScopeCode" placeholder="请选择房屋面积">
                <el-option v-for="item in housearealist" :key="item.areaScopeCode" :label="item.areaScopeName" :value="item.areaScopeCode">
                </el-option>
              </el-select>
              <el-select v-model="ruleForm.goodsregion[index].areaHouseCode" placeholder="请选择房屋户型" @visible-change="getHouseTypeList">
                <el-option v-for="item in houseTypeVos" :key="item.areaHouseCode" :label="item.areaHouseName" :value="item.areaHouseCode">
                </el-option>
              </el-select>
              <el-button icon="el-icon-plus" style="background-color:#fd804c;color: #fff;" v-if="index === 0" @click="addgoodsregion"></el-button>
              <el-button icon="el-icon-minus" style="background-color:#fd804c;color: #fff;" v-if="index !== 0" @click="deletgoodsregion(index)"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="套餐上下架" prop="resource">
            <el-radio-group v-model="ruleForm.resource">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="套餐商品选择" prop="goodsPackageDetails">
            <div class="checkDete" v-for="(item, index) in ruleForm.goodsPackageDetails" :key="index" style="margin-bottom:5px;">
              <el-select v-model="ruleForm.goodsPackageDetails[index].areaCode" placeholder="请选择区域" @change="value => changeArea(value, index)">
                <el-option v-for="item in arealist" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                </el-option>
              </el-select>
              <el-select v-model="ruleForm.goodsPackageDetails[index].classifyCode" placeholder="请选择商品分类" @change="value => changeClass(value, index)">
                <el-option v-for="item in serveclasslist" :key="item.classifyCode" :label="item.classifyName" :value="item.classifyCode">
                </el-option>
              </el-select>
              <el-select v-model="ruleForm.goodsPackageDetails[index].goodsCode" placeholder="请选择商品" @visible-change="value => getGoodsCodeList(index, value)" :loading="isloading">
                <el-option v-for="item in ruleForm.goodsPackageDetails[index]
                    .goodsCodeList" :key="item.goodsCode" :label="item.goodsName" :value="item.goodsCode">
                </el-option>
              </el-select>
              <el-select v-model="ruleForm.goodsPackageDetails[index].skuId" placeholder="请选择规格" @visible-change="value => getCraftSelectedVos(index, value)">
                <el-option v-for="item in ruleForm.goodsPackageDetails[index]
                    .craftSelectedVos" :key="item.skuId" :label="item.skuName" :value="item.skuId">
                </el-option>
              </el-select>
              <el-button icon="el-icon-plus" style="background-color:#fd804c;color: #fff;" v-if="index === 0" @click="addGoodsPackageDetails"></el-button>
              <el-button icon="el-icon-minus" style="background-color:#fd804c;color: #fff;" v-if="index !== 0" @click="deleteGoodsPackageDetails(index)"></el-button>
            </div>
          </el-form-item>
          <!-- <el-form-item label="推荐套餐选择" prop="goodsPkgCode">
            <div class="linput" v-for="(item, index) in ruleForm.goodsPkgCodeList" :key="index">
              <el-select v-model="ruleForm.goodsPkgCodeList[index].goodsPkgCode" placeholder="推荐套餐选择">
                <el-option
                  v-for="item in goodspkglist"
                  :key="item.goodsPkgCode"
                  :label="item.goodsPkgName"
                  :value="item.goodsPkgCode">
                </el-option>
              </el-select>
              <el-button icon="el-icon-plus"                   style="background-color:#fd804c;color: #fff;" v-if="index === 0" @click="addgoodsPkgCodeList" style="margin-left:10px;"></el-button>
              <el-button icon="el-icon-minus"                   style="background-color:#fd804c;color: #fff;" v-if="index !== 0" @click="deletegoodsPkgCodeList(index)" style="margin-left:10px;"></el-button>
            </div>
          </el-form-item> -->
          <el-form-item label="可售时段" prop="sellTimeIntervals">
            <!-- <div v-if="ruleForm.times==0">
              <el-time-select placeholder="起始时间" v-model="startTime" :picker-options="{start: '08:00',step: '00:30',end: '21:00'}">
              </el-time-select>
              <el-time-select placeholder="结束时间" v-model="endTime" @change="chooseTime" :picker-options="{start: '08:00',step: '00:30',end: '21:00',minTime: startTime}">
              </el-time-select>
            </div> -->
            <el-time-select v-model="sellTimeInterval" format="HH:mm" @change="chooseTimeInterval" placeholder="选择可售时间点" :picker-options="{start: '08:00',step: '00:30',end: '21:00'}">
            </el-time-select>
            <!-- <el-radio-group v-model="ruleForm.times" style="margin-left:15px">
              <el-radio :label="1" @change="empty">整点形式</el-radio>
              <el-radio :label="0" @change="empty">时段形式</el-radio>
            </el-radio-group> -->
          </el-form-item>
          <el-form-item>
            <div>
              <el-tag v-for="(tag, i) in ruleForm.sellTimeIntervals" :key="i" closable type="success" @close="tagClose(tag)">
                {{ tag }}
              </el-tag>
            </div>
            <!-- <div v-if="ruleForm.times==0">
              <el-tag v-for="(tag, i) in ruleForm.sellTimeIntervals" :key="i" closable type="success" @close="tagClose(tag)">
                {{ tag }}
              </el-tag>
            </div> -->
          </el-form-item>
          <div class="buttons">
            <el-button style="background-color:#fd804c;color: #fff;" @click="submitForm('ruleForm')">下一步</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import Bus from "../../../api/bus";
import moment from "moment";
export default {
  data () {
    // 商品套餐选择规则
    var checkgoodsPackageDetails = (rule, value, callback) => {
      value.forEach(item => {
        if (
          item.areaCode == "" ||
          item.classifyCode == "" ||
          item.goodsCode == "" ||
          item.skuId == ""
        ) {
          return callback(new Error("请完整选择套餐商品"));
        }
      });
      callback();
    };
    // 房屋面积配置规则
    var checkgoodsregion = (rule, value, callback) => {
      value.forEach(item => {
        if (
          item.areaScopeCode == "" ||
          item.areaHouseCode == ""
        ) {
          return callback(new Error("请完整选择房屋面积配置"));
        }
      });
      callback();
    };
    return {
      isloading: true,
      falg: true,
      region: '',
      startTime: '',
      endTime: '',
      ruleForm: {
        name: "",
        describe: "",
        orderdescribe: "",
        tagname: "",
        resource: 0,
        times: 1,
        areaHouseCode: '',
        goodsPackageDetails: [
          {
            areaCode: "",
            classifyCode: "",
            goodsCode: "",
            skuId: "",
            goodsCodeList: [],
            craftSelectedVos: []
          }
        ],
        goodsregion: [
          {
            areaScopeCode: "", // 房屋面积
            areaHouseCode: "", //房屋户型
          }
        ],
        goodsPkgCodeList: [
          {
            goodsPkgCode: "",
            goodsPkgName: ""
          }
        ],
        sellTimeIntervals: [] // 用户选择的可售时间列表
      },
      rules: {
        name: [
          { required: true, message: "请输入套餐名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur"
          }
        ],
        goodsregion: [
          { required: true, message: "请选择房屋面积配置", trigger: "change" },
          { validator: checkgoodsregion }
        ],
        resource: [
          { required: true, message: "请选择套餐上下架", trigger: "change" }
        ],
        sellTimeIntervals: [
          { required: true, message: "请完整选择可售时间", trigger: "change" }
        ],
        goodsPackageDetails: [
          { required: true, message: "请选择套餐商品" },
          { validator: checkgoodsPackageDetails }
        ]
      },
      arealist: [], //区域
      serveclasslist: [],
      housearealist: [],
      goodspkglist: [],
      houseTypeVos: [], // 当前房屋户型枚举
      sellTimeInterval: ""
    };
  },
  activated () {
    Bus.$on("falg", data => {
      this.falg = data;
    });
  },
  methods: {
    chooseTime () {
      this.ruleForm.sellTimeIntervals.push(this.startTime + '~' + this.endTime)
      this.startTime = "";
      this.endTime = "";
    },
    //添加房屋配置
    addgoodsregion () {
      this.houseTypeVos = []
      this.ruleForm.goodsregion.push({
        areaScopeCode: "",
        areaHouseCode: "",
      });
    },
    //删除房屋配置
    deletgoodsregion (index) {
      this.ruleForm.goodsregion.splice(index, 1);
    },
    //下一步
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          //   alert("submit!");
          // 套餐中不可配置相同的商品
          const flag = this.checkHasSameGoodsCode();
          if (flag) {
            this.$message.error(
              "配置商品套餐不可添加相同的商品,相同的商品请仅保留一条"
            );
            return false;
          }
          // 新增时推荐套餐不能添加相同的套餐
          const newflag = this.checkHasSamePackageCode();
          if (newflag) {
            this.$message.error("推荐套餐不能添加相同的套餐");
            return false;
          }
          // 可售时段为必填
          if (this.ruleForm.sellTimeIntervals.length == 0) {
            this.$message.error("可售时段为必填项");
            return false;
          }
          this.falg = false;
          Bus.$emit("falg2", true);
          Bus.$emit("goodsPackageDetails", this.ruleForm.goodsPackageDetails);
          // 首页参数拼接
          const goodsPackageRecommends = this.ruleForm.goodsPkgCodeList.map(
            item => {
              const newobj = {};
              newobj.goodsPackageRecommendCode = item.goodsPkgCode;
              return newobj;
            }
          );
          const goodsPackageDetails = this.ruleForm.goodsPackageDetails.map(
            item => {
              const newobj = {};
              newobj.areaCode = item.areaCode;
              newobj.subClassifyCode = item.classifyCode;
              newobj.goodsCode = item.goodsCode;
              newobj.skuId = item.skuId;
              return newobj;
            }
          );
          Bus.$emit("page1Msg", {
            goodsPackageBase: {
              doubleCodeList: this.ruleForm.goodsregion,
              goodsPackageCustomizableDescription: this.ruleForm.orderdescribe,
              goodsPackageDescription: this.ruleForm.describe,
              goodsPackageName: this.ruleForm.name,
              goodsPackageTag: this.ruleForm.tagname,
              isPutAway: this.ruleForm.resource,
              sellTimeIntervals: this.ruleForm.sellTimeIntervals // 新增可售时间字段
            },
            goodsPackageRecommends,
            goodsPackageDetails
          });
        } else {
          // console.log("error submit!!");
          // this.falg = false;
          // Bus.$emit("falg", true, "子组件向兄弟组件传值");
          this.falg = true;
          // Bus.$emit('falg', false)
          return false;
        }
      });
    },
    // 区域枚举
    getServiceAreaSelectedList () {
      this.$http({
        url: "/hssgoodsadmin/serviceGoodsPkg/getServiceAreaSelectedList",
        method: "get"
      }).then(res => {
        const { data } = res;
        this.arealist = data;
      });
    },
    // 服务分类
    getServiceClassifySelectedList () {
      this.$http({
        url: "/hssgoodsadmin/serviceGoodsPkg/getServiceClassifySelectedList",
        method: "get"
      }).then(res => {
        const { data } = res;
        this.serveclasslist = data;
      });
    },
    // 房屋面积枚举
    getHouseAreaList () {
      this.$http({
        url: "/hsssystemadmin/houseAreaMapping/getHouseAreaList",
        method: "get"
      }).then(res => {
        const { data } = res;
        this.housearealist = data;
      });
    },
    // 推荐套餐枚举
    GoodsPkgSelectedList () {
      this.$http({
        url: "/hssgoodsadmin/serviceGoodsPkg/getServiceGoodsPkgSelectedList",
        method: "get"
      }).then(res => {
        const { data } = res;
        this.goodspkglist = data;
      });
    },
    // 增加商品选择item
    addGoodsPackageDetails () {
      this.ruleForm.goodsPackageDetails.push({
        areaCode: "",
        classifyCode: "",
        goodsCode: "",
        skuId: "",
        goodsCodeList: [],
        craftSelectedVos: []
      });
    },
    // 删除商品选择item
    deleteGoodsPackageDetails (index) {
      this.ruleForm.goodsPackageDetails.splice(index, 1);
    },
    // 增加推荐套餐item
    addgoodsPkgCodeList () {
      // 非空判断校验
      let flag = true;
      this.ruleForm.goodsPkgCodeList.forEach(item => {
        if (item.goodsPkgCode == "") {
          flag = false;
        }
      });
      if (!flag) {
        this.$message.error("请先填写完整");
        return false;
      }
      this.ruleForm.goodsPkgCodeList.push({
        goodsPkgCode: "",
        goodsPkgName: ""
      });
    },
    // 删除推荐套餐item
    deletegoodsPkgCodeList (index) {
      this.ruleForm.goodsPkgCodeList.splice(index, 1);
    },
    // 商品枚举查询
    async getGoodsCodeList (index, value) {
      if (
        value &&
        this.ruleForm.goodsPackageDetails[index].areaCode != "" &&
        this.ruleForm.goodsPackageDetails[index].classifyCode != ""
      ) {
        const { data } = await this.$http({
          url: "/hssgoodsadmin/serviceGoodsPkg/getServiceGoodsSelectedList",
          method: "get",
          params: {
            areaCode: this.ruleForm.goodsPackageDetails[index].areaCode,
            classifyCode: this.ruleForm.goodsPackageDetails[index].classifyCode
          }
        });
        this.isloading = false;
        this.ruleForm.goodsPackageDetails[index].goodsCodeList = data;
      }
    },
    // 获取商品规格枚举
    getCraftSelectedVos (index, value) {
      const currentareaCode = this.ruleForm.goodsPackageDetails[index].areaCode;
      const currentclassifyCode = this.ruleForm.goodsPackageDetails[index]
        .classifyCode;
      const currentgoodsCode = this.ruleForm.goodsPackageDetails[index]
        .goodsCode;
      if (
        value &&
        currentareaCode != "" &&
        currentclassifyCode != "" &&
        currentgoodsCode != ""
      ) {
        const currentObj = this.ruleForm.goodsPackageDetails[
          index
        ].goodsCodeList.find(item => item.goodsCode === currentgoodsCode);
        this.ruleForm.goodsPackageDetails[index].craftSelectedVos =
          currentObj.craftSelectedVos;
      }
    },
    // 获取房屋户型枚举
    getHouseTypeList (value) {
      console.log(value)
      this.ruleForm.goodsregion.forEach(e => {
        this.region = e.areaScopeCode
        this.areaHouseCode = e.areaHouseCode
      })
      if (value) {
        const findObj = this.housearealist.find(
          item => item.areaScopeCode === this.region
        );
        console.log(findObj)
        if (findObj != null) {
          this.houseTypeVos = findObj.houseTypeVos;
        } else {
          this.$message.error('请先选择房屋面积')
        }
      }
    },
    // 区域值改变
    changeArea (value, index) {
      this.ruleForm.goodsPackageDetails[index].goodsCode = "";
      this.ruleForm.goodsPackageDetails[index].skuId = "";
    },
    changeClass (value, index) {
      this.ruleForm.goodsPackageDetails[index].goodsCode = "";
      this.ruleForm.goodsPackageDetails[index].skuId = "";
    },
    // 校验是否选择了相同的商品
    checkHasSameGoodsCode () {
      const goodsCodeList = [];
      this.ruleForm.goodsPackageDetails.forEach(item => {
        if (goodsCodeList.indexOf(item.goodsCode) === -1) {
          goodsCodeList.push(item.goodsCode);
        }
      });
      if (goodsCodeList.length < this.ruleForm.goodsPackageDetails.length) {
        return true;
      } else {
        return false;
      }
    },
    // 校验是否选择了相同的套餐
    checkHasSamePackageCode () {
      const goodsPkgCodeList = [];
      this.ruleForm.goodsPkgCodeList.forEach(item => {
        if (goodsPkgCodeList.indexOf(item.goodsPkgCode) === -1) {
          goodsPkgCodeList.push(item.goodsPkgCode);
        }
      });
      if (goodsPkgCodeList.length < this.ruleForm.goodsPkgCodeList.length) {
        return true;
      } else {
        return false;
      }
    },
    //清空
    empty () {
      this.tagClose()
      this.ruleForm.sellTimeIntervals = []
    },
    // 用户选择可售时段
    chooseTimeInterval (t) {
      if (t !== null) {
        let time = t;
        if (this.ruleForm.sellTimeIntervals.indexOf(time) === -1) {
          this.ruleForm.sellTimeIntervals.push(time);
        }
      }
      this.sellTimeInterval = "";
    },
    // 删除所选的可售时段
    tagClose (tag) {
      let tagList = this.ruleForm.sellTimeIntervals;
      tagList.splice(tagList.indexOf(tag), 1);
    }
  },
  mounted () {
    this.getServiceAreaSelectedList();
    this.getServiceClassifySelectedList();
    this.getHouseAreaList();
    this.GoodsPkgSelectedList();
  }
};
</script>
<style scoped lang='scss'>
.basic {
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}
// /deep/ .el-form-item__content {
//   display: flex;
//   align-items: center;
// }
.Useful {
  font-size: 18px;
  margin-bottom: 15px;
}
.checkDete {
  display: flex;
}
.checkDete .el-select {
  width: 120px;
  margin-right: 10px;
}
.linput {
  display: flex;
  margin-bottom: 5px;
}
.linputc {
  width: 150px;
  margin-left: 10px;
}
.buttons {
  text-align: center;
  position: absolute;
  bottom: -70px;
  left: 50%;
  transform: translateX(-50%);
}
.el-tag {
  margin-right: 10px;
}
</style>
